package me.zingon.open.bigsmart.queue;

import lombok.extern.slf4j.Slf4j;
import me.zingon.open.bigsmart.constant.JOB_STATUS;
import me.zingon.open.bigsmart.model.Job;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author ztc 1423047407@qq.com
 * @version 1.0
 * @date 2020-8-6 11:11
 */
@Component
@Slf4j
public class JobPoll {

    @Autowired
    RedisTemplate redisTemplate;

    @Value("${redis.prefix.jobPoll}")
    String PREFIX;

    HashOperations hashOperations;

    @PostConstruct
    private void init(){
        hashOperations = redisTemplate.opsForHash();
    }

    public boolean add(Job job){
        try {
            String key = PREFIX + job.getTopic();
            String hkey = job.getId().toString();
            hashOperations.put(key, hkey, job);
            return true;
        }catch (Exception e){
            log.error("job添加jobPoll失败{}",e);
            return false;
        }
    }

    /**
     * TODO: 2020-8-6 加锁 set ex nx
     */
    public boolean changeStatus(String topic,String id, JOB_STATUS jobStatus){
        try {
            String key = PREFIX + topic;
            Job job = (Job) hashOperations.get(key, id);
            job.setStatus(jobStatus.getCode());
            this.add(job);
            return true;
        }catch (Exception e){
            log.error("job修改状态失败{}",e);
            return false;
        }
    }

    /**
     * TODO: 2020-8-6 加锁 set ex nx
     */
    public Job getById(String topic,String id){
        String key = PREFIX + topic;
        Job job=(Job) hashOperations.get(key,id);
        return job;
    }

    public boolean rm(String topic,String id){
        try {
            String key = PREFIX + topic;
            hashOperations.delete(key, id);
            return true;
        }catch (Exception e){
            log.error("JobPoll 删除失败：{}",e);
            return false;
        }
    }

}
